<template>
  <div class="varable-manage">
    <div class="pcocess-config__center">
      <div class="process-config-wrap">
        <div class="title">
          动态表单模版可以用来在呼叫、会话、客户联络等场景下记录服务内容，支持使用自定义字段组建不同的动态表单模板，应用于各种服务场景
        </div>
        <div>
          <span class="icon-text" @click.stop="exportAct('add')"><i class="el-icon-plus"></i>添加</span>
          <span class="icon-text" @click.stop="exportAct('refresh')"><i class="iconfont icon-shuaxin"></i>刷新</span>
        </div>
        <el-table :data="tableList" size="mini" style="width: 100%">
          <el-table-column type="index" width="50"> </el-table-column>
          <el-table-column prop="name" label="模版名称" :show-overflow-tooltip="true"> </el-table-column>
          <el-table-column prop="description" label="模版描述" :show-overflow-tooltip="true">
            <template scope="scope">
              {{scope.row.description || '--'}}
            </template>
          </el-table-column>
          <el-table-column prop="scenesName" label="应用场景"></el-table-column>
          <el-table-column prop="fieldNames" label="包含字段"></el-table-column>
          <el-table-column label="操作">
            <template scope="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="changeStatus(scope.row)"
              />
              <span class="edit-btn main-color" @click.stop="handleEdit(scope.row)">{{ $t('public.edit') }}</span>
              <span class="del-btn" v-if="scope.row.category !== 'system'" @click.stop="deleteTempl(scope.row)">{{
                $t('public.delete')
              }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <left-slide
      width="800px"
      :visible.sync="slideLeft"
      :title="operType === 'add' ? '添加模版' : '编辑模版'"
      @saveClick="handleSaveClick"
      @cancelClick="cancelClick"
      :showFooter="true"
    >
      <div style="margin: 20px">
        <edit-temp
          ref="editTemp"
          :globalFieldsObj="globalFieldsObj"
          @updateSuccess="updateSuccess"
          :globalFields="globalFields"
        ></edit-temp>
      </div>
    </left-slide>
  </div>
</template>
<script>
import editTemp from './editTemp.vue'
import { cloneDeep } from 'lodash'
import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
export default {
  name: 'variableManage',
  data() {
    return {
      globalFieldsObj: {},
      globalFields: [],
      operType: '',
      scenesOptions: {
        callCenter: '呼叫中心',
        imLeaveMsg: '在线-留言'
      },
      slideLeft: false,
      dataList: [],
      currVarObj: '',
      tableList: []
    }
  },
  components: {
    editTemp,
    leftSlide
  },
  methods: {
    deleteTempl(data) {
      this.$confirm(`请确认要删除该模版？`, this.$t('public.tip'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn',
        type: 'warning'
      }).then(() => {
        this.$store
          .dispatch('delDynamicformById', {
            _id: data._id
          })
          .then((res) => {
            if (res && res.success) {
              this.$message.success('删除模版成功')
              this.fetchData()
            } else {
              this.$message.error('删除模版失败')
            }
          })
      })
    },
    changeStatus(data) {
      this.$confirm(`请确认是否${data.status ? '启用' : '停用'}该模版？`, this.$t('public.tip'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn',
        type: 'warning'
      }).then(() => {
        console.log(data)
        let dataNew = {
          _id: data._id,
          status: data.status
        }
        this.$store.dispatch('updateDynamicTemplate', dataNew).then((res) => {
          if (res && res.success) {
            this.$message.success('操作成功')
            this.fetchData()
          } else {
            this.$message.error('操作失败')
          }
        })
      }).catch(() => {
        data.status = data.status ? 0 : 1
      })
    },
    updateSuccess() {
      this.operType = ''
      this.slideLeft = false
      this.fetchData()
    },
    //        添加刷新生效方法接收
    exportAct(val) {
      if (val === 'add') {
        this.operType = 'add'
        this.slideLeft = true
        this.$nextTick(() => {
          this.$refs.editTemp.open('add', {})
        })
      } else if (val === 'refresh') {
        this.fetchData()
      }
    },
    cancelClick() {
      this.slideLeft = false
    },
    handleSaveClick() {
      this.$refs.editTemp.save()
    },
    getFields(fields) {
      const fieldsArr = fields.map((v) => {
        const obj = this.globalFieldsObj[v.field]
        if (obj) {
          return obj.name
        }
      })
      return fieldsArr.join('、')
    },
    getScenes(scenes) {
      const scenesArr = scenes.map((v) => {
        return this.scenesOptions[v]
      })
      return scenesArr.join('、')
    },
    fetchData() {
      this.$store.dispatch('queryDynamicform', { scenes: [] }).then((resp) => {
        if (resp && resp.success) {
          const arr = (resp.data.list || []).map((item) => {
            // 场景处理
            if (item.scenes && item.scenes.length) {
              item.scenesName = this.getScenes(item.scenes)
            }
            // 包含字段处理
            if (item.fields && item.fields.length) {
              item.fieldNames = this.getFields(item.fields)
            }
            return item
          })
          console.log(arr)
          this.tableList = arr
        }
      })
    },
    handleEdit(row) {
      this.slideLeft = true
      this.operType = 'edit'
      this.$nextTick(() => {
        this.$refs.editTemp.open('edit', cloneDeep(row))
      })
    }
  },
  activated () {
    this.$store.dispatch('getDicCache', { type: 'globalfield' }).then((res) => {
      if (res.success) {
        this.globalFields = res.data || []
        const obj = {}
        this.globalFields.map((item) => {
          obj[item.field] = item
        })
        this.globalFieldsObj = obj
      }
      this.fetchData()
    })
  },
  beforeMount() {
    this.$store.dispatch('getDicCache', { type: 'globalfield' }).then((res) => {
      if (res.success) {
        this.globalFields = res.data || []
        const obj = {}
        this.globalFields.map((item) => {
          obj[item.field] = item
        })
        this.globalFieldsObj = obj
      }
      this.fetchData()
    })
  }
}
</script>

<style lang="stylus" scoped>
.icon-text
  margin-right 16px
  cursor pointer
  line-height 30px
  i {
    color: #459ae9;
    font-size: 12px;
    margin-right: 2px;
  }
.varable-manage
  padding: 20px;
  height: calc(100vh - 95px);
  overflow-y: auto;
  font-size: 12px;
  .edit-btn
    margin-left: 10px
  .title
    color #3b5998
    height 30px
    line-height 30px
    padding 3px 10px
    overflow hidden
    text-overflow ellipsis
    max-width 100%
    white-space nowrap
    cursor pointer
  .margin-t-15
    margin-top 15px
  .margin-l-10
    margin-left 10px
  .pag-wapper
    position: absolute;
    right: 15px;
    top: 14px;
  .del-btn
    cursor pointer
    color: #ff6b6b
    margin-left 10px
  .main-color
    color #459ae9
    cursor pointer
  .wapper
    display flex
    flex-direction column
  .tool
    position relative
    border 1px solid #e7e7eb
    border-bottom 0
    padding  12px 15px
    /*display flex*/
    justify-content space-between
  .primary_btn
    padding 0px 10px
    min-width 60px
  .del
    color #ff6b6b
</style>
